LIBRARY ieee;
USE ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;
use ieee.numeric_std.all;

entity vga_driver is
  port (clk : in std_logic;
		rstn : in std_logic;
		hsync_i : in std_logic;
		vcounter : in integer;
		r_in : in std_logic_vector(7 downto 0);
		g_in : in std_logic_vector(7 downto 0);
		b_in : in std_logic_vector(7 downto 0);
		r_out : out std_logic_vector(3 downto 0);
		g_out : out std_logic_vector(3 downto 0);
		b_out : out std_logic_vector(3 downto 0);
		h_address : out std_logic_vector(8 downto 0);
		vsync : out std_logic;
		hsync : out std_logic);
end entity;

architecture rtl of vga_driver is
  signal hcounter : integer;
begin
	process(vcounter)
	begin
		if (vcounter = 0 or vcounter = 1) then
			vsync <= '0';
		else
			vsync <= '1';
		end if;
	end process;
	
	process(hcounter)
	begin
		if (hcounter < 95) then
			hsync <= '0';
		else
			hsync <= '1';
		end if;
	end process;
	
	process (rstn, clk)
	begin
		if rstn = '0' then
			hcounter <= 0;
		else
			if rising_edge(clk) then
				if hsync_i = '0' then
					hcounter <= 0;
				else
					hcounter <= hcounter + 1;
				end if;
			end if;
		end if;
	end process;
	
	process(hcounter)
	begin
		h_address <= std_logic_vector(to_unsigned((hcounter - 183) / 2, 9));
	end process;
			
	process (hcounter, vcounter, r_in, g_in, b_in)
	begin
		if rising_edge(clk) then
			if (hcounter >= 184 and
				hcounter < 824 and
				vcounter >= 42 and
				vcounter < 522) then
				r_out <= r_in(7 downto 4);
				g_out <= g_in(7 downto 4);
				b_out <= b_in(7 downto 4);
			else
				r_out <= "0000";
				g_out <= "0000";
				b_out <= "0000";
			end if;
		end if;
	end process;
end rtl;

